<?php
namespace app\workerman\controller;
use app\admin\model\Equipment;
use app\admin\model\Origin;
use app\common\model\Test;
use GatewayWorker\Lib\Gateway;
class WorkerEvents
{
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param $client_id //连接id
     */
    public static function onConnect($client_id)
    {
        Test::create(['title'=>'连接触发','content'=>$client_id,'activitytime'=>date('Y-m-d H:i:s')]);
    }

    /**
     * origin 1千梦 2电机
     * 当客户端发来消息时触发
     * @param $client_id //连接id
     * @param mixed $message 具体消息
     */
    public static  function onMessage($client_id, $message)
    {
        if($message != '{"action": "heartbeat"}'){
            Test::create(['title'=>'原始信息','content'=>$message,'activitytime'=>date('Y-m-d H:i:s')]);
        }
        $message = html_entity_decode($message);
        $data = json_decode($message,true);
        if(isset($data['action'])&&$data['action']){
            switch ($data['action']){
                case 'heartbeat':
                    $message = ['action'=>'heartbeat'];
//                    $message = '{"action":"heartbeat"}';
                    self::send($message);
                    break;
                case 'login':
                    //登陆
                    $dd = isset($data['data']) ? $data['data'] : [];
                    $mNum = isset($dd['mNum']) ? $dd['mNum'] : '';
                    $mCode = isset($dd['mCode']) ? $dd['mCode'] : 0;
                    $origin = isset($data['origin']) ? $data['origin'] ? $data['origin'] : 2 : 2;//1千梦 2电机
                    $equipment_model = Equipment::where(['mNum'=>$mNum])->find();
                    if($equipment_model){
                        $equipment_model->save(['client_id'=>$client_id]);
                        $origin_model = Origin::where(['rid'=>$equipment_model['id'],'origin'=>$origin])->find();
                        if($origin_model){
                            //根据来源查到了之前连接的 更新会话id
                            Origin::where(['rid'=>$equipment_model['id'],'origin'=>$origin])->update(['client_id'=>$client_id]);
                        }else{
                            //新连接的 新建记录
                            Origin::create(['client_id'=>$client_id,'rid'=>$equipment_model['id'],'origin'=>$origin]);
                        }
                        $message = ['action'=>'loginOK','data'=>['code'=>200,'msg'=>'login success']];
//                        $message = '{"action": "loginOK","data": {"code": "200", "msg": "login success"}}';
                    }else{
                        $message = ['action'=>'loginFail','data'=>['code'=>400,'msg'=>'登陆失败信息']];
//                        $message = '{"action": "loginFail","data": {"code": "400", "msg": "登陆失败信息"}}';
                    }
                    self::sendLog($message,$client_id);
                    if($equipment_model){
                        usleep(200000);
                        //登陆后下发充币通知
                        $message = ['action'=>'chargeCions','rid'=>$equipment_model['id'],'price'=>$equipment_model['price'],'data'=>['count'=>$equipment_model['game_currency']]];
//                        $message = '{"action": "chargeCions","data": {"count": "'.$equipment_model['game_currency'].'"},"rid":"'.$equipment_model['id'].'"}';
                        self::sendLog($message,$client_id);
                    }
                    break;
                case 'getInventory':
                    //查询库存
                    $rid = isset($data['rid']) ? $data['rid'] : '';//id
                    $equipment_model = Equipment::where(['id'=>$rid])->find();
                    $message = [
                        'action'=>'putInventory',
                        'rid'=>$rid,
                        'data'=>[
                            'num'=>$equipment_model['inventory']
                        ]
                    ];
                    self::sendLog($message,$client_id);
                    break;
                case 'coinsAdd':
                    //客户端反馈充币成功
                    $rid = isset($data['rid']) ? $data['rid'] : '';//id
                    $dd = isset($data['data']) ? $data['data'] : [];
                    $count = isset($dd['count']) ? $dd['count'] : 1;//数量
                    $t = isset($dd['t']) ? $dd['t'] : 1;//1线下手动投币 2线上套餐充币
                    //服务端发送出货通知
//                    $equipment_model = Equipment::where(['id'=>$rid])->find();
                    //获取到电机对应的会话id给电机发送出货通知
                    $origin = Origin::where(['rid'=>$rid,'origin'=>2])->find();
                    if($origin){
                        $equipment_model = Equipment::where(['id'=>$rid])->find();
                        switch ($equipment_model['inventory']){
                            case '8':
                            case '7':
                                $boxNum = '0101';
                                break;
                            case '6':
                            case '5':
                                $boxNum = '0102';
                                break;
                            case '4':
                            case '3':
                                $boxNum = '0104';
                                break;
                            case '2':
                            case '1':
                                $boxNum = '0105';
                                break;
                            default:
                                $boxNum = '';
                                break;
                        }
                        $message = [
                            'action'=>'putOutBox',
                            'rid'=>$rid,
                            'boxNums'=>[
                                ['boxNum'=>$boxNum,'count'=>1]
                            ]
                        ];
//                        $message = '{"action":"putOutBox","rid":"'.$rid.'","boxNums":[{"boxNum":"0101","count":1}]}';
//                        $message = '{"action": "putOutBox","data": {"boxNums":[{"boxNum":"0102","count":"1","price":"1"}]},"rid":"'.$rid.'"}';
                        self::sendIdLog($message,$origin['client_id']);
                        self::sendLog($message,$client_id);
                    }else{
                        //电机没连接ws 回报给客户端
                        self::sendLog('电机未连接',$client_id);
                    }

                    break;
                case 'mchOut':
                    //{"action":"coinsAdd" , "rid":'1', "data":{"count" : "投币数量" , "t": 1}}
                    //客户端→服务器:上报服务器出货结果
                    $mNum = isset($data['mNum']) ? $data['mNum'] : '';//设备编号
                    $rid = isset($data['rid']) ? $data['rid'] : '';//唯一id
                    $st = isset($data['st']) ? $data['st'] : '';//出货状态 1出货成功 2出货失败
                    $ifo = isset($data['ifo']) ? $data['ifo'] : '';//出货失败货道
                    $ifo_s = isset($data['ifo_s']) ? $data['ifo_s'] : '';//出货成功货道
                    $origin = Origin::where(['rid'=>$rid,'origin'=>1])->find();
                    if($st == 1){
                        $equipment_model = Equipment::where(['id'=>$rid])->find();
                        if($equipment_model['inventory']>0){
                            Equipment::where(['id'=>$rid])->update(['inventory'=>$equipment_model['inventory']-1]);
//                            $equipment_model = Equipment::where(['id'=>$rid])->find();
//                            if($equipment_model['inventory'] == 1){
//
//                            }
                        }
                        //出货成功  服务器→客户端:服务器下发玩家中奖后的取货
                        $message = ['action'=>'so','st'=>'成功','id'=>$rid];
//                        $message = '{"action": "so","st": "成功","id":"'.$rid.'"}';
                        self::sendIdLog($message,$origin['client_id']);
                        //self::sendLog($message);
                    }else{
                        //出货失败
                        $message = ['action'=>'so','st'=>'失败','id'=>$rid];
//                        $message = '{"action": "so","st": "失败","id":"'.$rid.'"}';
                        self::sendIdLog($message,$origin['client_id']);
                    }
                    break;
                case 'co':
                    //客户端→服务器:上报服务器出货结果  我感觉应该是取货
                    $id = isset($data['id']) ? $data['id'] : '';//唯一标识
                    $t = isset($data['t']) ? $data['t'] : '';//出货状态 3出货成功 4出货失败
                    break;
                case 'power':
                    $bns = isset($data['bns']) ? $data['bns'] : '';//设备编号
                    $message = ['action'=>'cpr','isb'=>'0','bn'=>json_encode($bns)];
//                    $message = '{"action": "cpr","isb": "0","bn":"'.$bns.'"}';
                    self::sendLog($message,$client_id);
                    break;
                default:
                    $message = '参数异常';
                    self::sendLog($message,$client_id);
                    break;
            }

            return '';
        }else{
            return self::sendLog('参数异常',$client_id);
        }
    }

    public function login($data){
        Test::create(['title'=>'登陆接收','content'=>json_encode($data),'activitytime'=>date('Y-m-d H:i:s')]);
        return GateWay::sendToCurrentClient(json_encode($data));
    }

    /**
     * 当用户断开连接时触发
     * @param $client_id //连接id
     */
    public static function onClose($client_id)
    {
        Test::create(['title'=>'断开触发','content'=>$client_id,'activitytime'=>date('Y-m-d H:i:s')]);
    }

    //发送并且记录日志
    public static function sendLog($message,$client_id){
        Test::create(['title'=>'发送消息给'.$client_id,'content'=>json_encode($message),'activitytime'=>date('Y-m-d H:i:s')]);
        return GateWay::sendToCurrentClient(json_encode($message));
    }
    //发送并且记录日志
    public static function send($message){
        return GateWay::sendToCurrentClient(json_encode($message));
    }
    //发送并且记录日志
    public static function sendIdLog($message,$client_id){
        Test::create(['title'=>'id发送消息给'.$client_id,'content'=>json_encode($message),'activitytime'=>date('Y-m-d H:i:s')]);
        return GateWay::sendToClient($client_id,json_encode($message));
    }
}